<?php
/**
 * @author Feng
 * @date 2012-5-28
 */
class controller_admin_picture_category extends system_user_control {
	
	private $pid = null;
	private $concept = null;
	public function init() {
		if(!parent::init()) {
			return ;
		}
		picture_category::$_lang = $this->user->getLang();
		$this->concept = new picture_category_localeConcept($this->user->getLang());
		$this->view->pid = $this->pid = intval($this->_param('parent'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Pictures'))->setRoute('picture/index'));
		$this->_crumbs()->addPage(system_nav_page::create($this->language('Categories'))->setRoute('picture/category/index'));
	}
		
	public function action_index() {
		$this->_goRoute('picture/category/list');
		$this->render();
	}
	
	public function action_addnew() {
		$row = $this->concept->create();
		$row->setParentId($this->pid);
		$row->setIsActive(1);
		$row->setDisplayOrder(0);
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_navPage();
		$this->_crumbs()->addPage(system_nav_page::create($this->language('New Category'))->setRoute('picture/category/addnew')->setParams(array('parent' => $this->pid)));
		$this->render('picture/category/row.phtml');
	}
	
	public function action_edit() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('category.id = ?' => $id)))) {
			throw new picture_exception("The Category is not Existing.");
		}		
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_navPage();
		$this->_crumbs()->addPage(system_nav_page::create($row->getLocale()->getTitle())->setRoute('picture/category/edit')->setParams(array('id' => $row->getId())));
		$this->render('picture/category/row.phtml');
	}
	
	public function action_move() {
		$id = intval($this->_param('id'));
		if(!($row = $this->concept->fetch(array('category.id = ?' => $id)))) {
			throw new picture_exception("The Category is not Existing.");
		}
		if($this->getRequest()->isPost()) {
			$this->referer = $this->_post('referer');
			try {
				if($this->_post('top')) {
					$row->setParentId(0);
					$row->save();
				} else {
					if(!($to = intval($this->_post('to')))) {
						throw new picture_exception("Please select a category you want to move to.");
					}
					$row->setParentId($to);
					$row->save();
				}
				$this->view->throwMessage = "Complete";
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_navPage();
		$this->_crumbs()->addPage(system_nav_page::create($this->language('MoveTo'))->setRoute('picture/category/move')->setParams(array('id' => $row->getId())));
		$this->render();
	}
	
	private function _saveRow($row) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}
		$manual = $this->_post('manualKeyNameCheck');
		if(!$row->getId() && !$manual) {
			$name = system_encrypt::createIdByTime();
		} else {
			$name = trim($this->_post('name'));
		}
		$this->view->manualKeyNameCheck = $manual ? true : false;
		$this->referer = $this->_post('referer');
		$row->getLocale()->setTitle(trim($this->_post('title')));
		$row->getLocale()->setDescription($this->_post('description'));
		$row->setName($name);
		$row->setParentId(intval($this->_post('parent_id')));
		$row->setDisplayOrder(intval($this->_post('display_order')));
		$row->setIsActive(intval($this->_post('is_active')) ? 1 : 0);
		$row->setIsRecommend(intval($this->_post('is_recommend')) ? 1 : 0);
		$this->_saveToDatabase($row, 'cover', 'image');
		return $row;
	}
	
	public function action_list() {
		$this->view->order = $order = strtolower($this->getRequest()->getQuery('order'));
		$_order = array("display_order ASC");
		if($order) {
			$this->view->sort = $sort = intval($this->getRequest()->getQuery('sort'));
			switch($order) {
				case 'date': {
					$order = 'lastmodified';
					break;
				}
				case 'special': {
					$order = 'locale.stotal';
					break;
				}
				default: {
					$sort = !$sort;
					$order = 'display_order';
					break;
				}
			}
			$_sort = !$sort ? 'DESC' : 'ASC';
			$_order = array("$order $_sort");
		}

		$concept = new picture_category_concept($this->user->getLang());
		$list = $concept->fetchAll(array('category.parent_id = ?' => $this->pid), $_order);
		$ids = $children = array();
		foreach($list AS $row) {
			$ids[] = $row->getId();
		}
		if(!empty($ids)) {
			$_ids = implode(', ', $ids);
			$sql = "SELECT a.`id`, (";
			$sql .= "SELECT COUNT(*) FROM `picture_category` AS `b` INNER JOIN `picture_category_locale` AS `l` ON `l`.`category_id` = `b`.`id` ";
			$sql .= "WHERE `b`.`parent_id` = `a`.`id` AND `l`.`lang` = '{$this->user->getLang()}'";
			$sql .= ") AS `count` FROM `picture_category` AS `a` WHERE `a`.`id` IN($_ids)";
			foreach(system_db::getAdapter()->query($sql) as $row) {
				$children[$row['id']] = $row['count'];
			}
		}
		if($this->getRequest()->isPost()) {
			try {
				$lang = $this->user->getLang();
				foreach((array)$this->getRequest()->getPost('display_order') AS $id => $value) {
					system_db::getAdapter()->query("UPDATE `picture_category` SET `display_order` = '$value' WHERE `id` = '$id'");
					system_db::getAdapter()->query("UPDATE `picture_category_locale` SET `stotal` = (
							SELECT COUNT(1) FROM `picture_special_category` WHERE `category_id` = '$id' AND `lang` = '$lang'
						) WHERE `lang` = '$lang' AND `category_id` = '$id'");
				}
				$this->view->throwMessage = 'Complete';
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}

		$this->view->children = $children;
		$this->view->list = $list;
		$this->_navPage();
		$this->render();
	}

	private function _navPage($id = null) {
		$this->_crumbs()->addPage(system_nav_page::create($this->language('List'))->setRoute('picture/category/list'));
		if(1 && $path = picture_category::categoryPath(($id === null ? $this->pid : $id))) {
			krsort($path);
			foreach($path AS $row) {
				$this->_crumbs()->addPage(system_nav_page::create($row->getTitle())->setRoute('picture/category/list')->setParams(array('parent' => $row->getId())));
			}
		}
	}
}
